package com.sun.dream.fish.secret.hash;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class HMACExample {
    public static void main(String[] args) {
        String input = "Hello World";
        String key = "MySecretKey";

        try {
            String hmacSha256 = calculateHMAC(input, key, "HmacSHA256");
            System.out.println("HMAC-SHA256 hash of \"" + input + "\": " + hmacSha256);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
    }

    public static String calculateHMAC(String message, String key, String algorithm)
            throws NoSuchAlgorithmException, InvalidKeyException {
        Mac mac = Mac.getInstance(algorithm);
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), algorithm);
        mac.init(secretKey);
        byte[] macBytes = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));

        return Base64.getEncoder().encodeToString(macBytes);
    }
}